package com.zhuyi.broadcast.controller;

import com.zhuyi.broadcast.mapper.ElementMapper;
import com.zhuyi.broadcast.pojo.domain.Element;
import com.zhuyi.broadcast.pojo.domain.Resource;
import com.zhuyi.broadcast.service.ElementService;
import com.zhuyi.broadcast.service.ResourceService;
import com.zhuyi.common.annotation.Log;
import com.zhuyi.common.config.ZhuYiConfig;
import com.zhuyi.common.core.controller.BaseController;
import com.zhuyi.common.core.domain.AjaxResult;
import com.zhuyi.common.core.page.TableDataInfo;
import com.zhuyi.common.enums.BusinessType;
import com.zhuyi.common.enums.FileCategoryEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.zhuyi.common.utils.file.FileUtils;
import com.zhuyi.common.utils.file.FileUploadUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;


/**
 * <p>
 *  资源Controller
 * </p>
 *
 * @author dyj
 * @since 2024-12-12
 */
@RestController
@RequestMapping("/broadcast/resource")
public class ResourceController extends BaseController {

    @Autowired
    private ResourceService resourceService;

    /**
     * 创建文件夹资源
     */
    @Log(title = "资源", businessType = BusinessType.INSERT)
    @PostMapping(value = "/folder/save")
    public AjaxResult createFolder(@RequestBody Resource resource) {
        Resource bcResource = resourceService.createFolderResource(resource);
        if (bcResource == null) {
            return error("找不到路径或者目录已存在");
        }
        return success(bcResource);
    }

    /**
     * 上传资源
     */
    @Log(title = "资源", businessType = BusinessType.INSERT)
    @PostMapping(value = "/file/upload")
    public AjaxResult uploadResource(HttpServletRequest request, @RequestPart MultipartFile file,
                                     @RequestParam(required = false) Long folderId,
                                     @RequestParam(required = false) String resourceName) throws IOException {
        String requestUrl = request.getRequestURL().toString();
        requestUrl = requestUrl.substring(0, requestUrl.indexOf("/broadcast"));

        // 如果提供了文件名，使用自定义的文件名
        String resourceFinalName = (resourceName != null && !resourceName.trim().isEmpty()) ? resourceName : file.getOriginalFilename();

        Resource sycResource = resourceService.uploadFileResource(file, folderId, requestUrl, resourceFinalName);
        return success(sycResource);
    }

//    /**
//     * 新增资源
//     */
//    @Log(title = "资源", businessType = BusinessType.INSERT)
//    @PostMapping(value = "/file/save")
//    public AjaxResult add(@RequestBody Resource resource)
//    {
//        return success(resourceService.insertResource(resource));
//    }

    /**
     * 查询资源（列表）
     */
    @Log(title = "资源")
    @GetMapping("/list")
    public TableDataInfo list(Resource resource, HttpServletRequest request)
    {
        startPage();
        String requestUrl = request.getRequestURL().toString();
        requestUrl = requestUrl.substring(0, requestUrl.indexOf("/broadcast"));
        List<Resource> list = resourceService.selectResourceList(resource, requestUrl);
        return getDataTable(list);
    }


    /**
     * 查询资源（单个）
     * 提供资源预览，包括资源名称、类型、大小、上传时间等信息
     */
    @Log(title = "资源")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(HttpServletRequest request, @PathVariable("id") Long id)
    {
        String requestUrl = request.getRequestURL().toString();
        requestUrl = requestUrl.substring(0, requestUrl.indexOf("/broadcast"));
        return success(resourceService.selectResourceById(id, requestUrl));
    }

    /**
     * 删除资源（彻底删除）
     * 删除时，判断资源类型（文件或文件夹），并根据类型删除
     * 对于文件夹，如果包含子文件夹和资源，则会一并删除
     */
    @Log(title = "资源", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {

        // 获取资源信息
        Resource resource = resourceService.getById(id);
        if (resource != null) {
            File sysFile;
            if (FileCategoryEnum.FOLDER.getCode().equals(resource.getResourceCategory())) {
                // 如果是文件夹，删除文件夹及其子文件
                sysFile = new File(ZhuYiConfig.getUploadPath() + resource.getResourcePath());
                FileUtils.deleteDirectory(sysFile);
            } else {
                // 如果是文件，直接删除文件
                sysFile = new File(FileUploadUtils.getFileRealPath(resource.getResourcePath()));
                FileUtils.deleteFile(sysFile.getAbsolutePath());
            }
        }
        return success(resourceService.deleteResourceById(id));
    }

    /**
     * 搜索资源（关键字）
     */
    @Log(title = "资源")
    @GetMapping("/search")
    public AjaxResult search(@RequestParam String keyword) {
        try {
            List<Resource> resources = resourceService.searchResources(keyword);
            return AjaxResult.success(resources);
        } catch (Exception e) {
            return AjaxResult.error("搜索资源失败：" + e.getMessage());
        }
    }
}
